<?php

namespace LRP\Tube;

use LRP\Contract\TubeInterface;
use LRP\Exception\ConnectionException;
use LRP\Task;

/**
 * Class RedisTube
 *
 * PHP Version > 7.0
 *
 * @package LRP\Tube
 * @author  Jon
 * @link    https://gitee.com/joncc/long-running-processor
 */
class RedisTube implements TubeInterface
{
    private $redis;

    private $tube;

    /**
     * RedisTube constructor.
     *
     * @param string $host
     * @param int $port
     * @param int $connectTimeout
     * @throws \Exception
     */
    public function __construct(string $host, int $port, int $connectTimeout)
    {
        if (!extension_loaded('redis')) {
            throw new ConnectionException('redis extension not found');
        }

        $this->redis = new \Redis();
        $this->redis->connect($host, $port, $connectTimeout);
    }

    /**
     * @param string $type
     * @return TubeInterface
     */
    public function type(string $type): TubeInterface
    {
        $this->tube = $type;

        return $this;
    }

    /**
     * @return string
     */
    public function getType(): string
    {
        return $this->tube;
    }

    /**
     * @param Task $task
     */
    public function push(Task $task): void
    {
        $this->redis->lPush($this->tube, serialize($task));
    }

    /**
     * @return mixed
     */
    public function pop()
    {
        $task = $this->redis->rPop($this->tube);
        return unserialize($task);
    }
}